<template>
  <div class="h-full overflow-y-auto">
    <PageHeader :title="$t('setting.店铺设置')" />
    <LangTabs v-model="lang" />

    <!-- 店铺基本信息 -->
    <div class="titleRow pl10 mb20">{{ $t("setting.店铺基本信息") }}</div>
    <el-table
      :data="basicInfoData"
      class="cover-table mb30"
      :show-header="false"
      style="width: 100%"
      border
      v-loading="loading"
    >
      <el-table-column prop="name" width="300px">
        <template #default="{ row }">
          <div class="flex justify-end">{{ row.name }}</div>
        </template>
      </el-table-column>
      <el-table-column prop="value">
        <template #default="{ row }">
          <div style="width: 100%" class="text-left">
            <div v-if="row.key === 'shopName'">
              <el-input
                v-model="formData['name' + lang]"
                style="width: 300px"
                :disabled="originTenantInfo['name' + lang]?.length > 0"
                :placeholder="$t('setting.请输入')"
              />
              <div class="fs-12 color-999999">
                {{ $t("setting.注店铺名称只能设置一次设置后不可更改") }}
              </div>
            </div>
            <div v-if="row.key === 'shopLogo'">
              <!-- <UploadFile
                v-model="formData.shopLogo"
                limit="1"
                :show-tip="false"
              /> -->
              <PickPicture v-model="formData.shopLogo" :limit="1" />
              <div class="fs-12 color-999999">
                {{ $t("setting.建议上传宽130像素高130像素的图片") }}
              </div>
            </div>
            <div v-if="row.key === 'tenantOpenStatus'">
              <el-switch
                v-model="formData.tenantOpenStatus"
                :active-value="1"
                :inactive-value="0"
              />
            </div>
            <div v-if="row.key === 'album'">
              <PickPicture v-model="formData.album" :limit="10" />
            </div>
            <div v-if="row.key === 'shopPhone'">
              <el-input
                v-model="formData.shopPhone"
                style="width: 300px"
                :placeholder="$t('setting.请输入用于交易联系的电话号码')"
              />
              <div class="fs-12 color-999999">
                {{
                  $t("setting.请输入用于交易联系的电话号码方便买家进行咨询沟通")
                }}
              </div>
            </div>
            <div v-if="row.key === 'shopAddress'">
              <el-cascader
                v-model="formData.shopAddress"
                :props="cascaderProps"
                style="width: 300px"
                :placeholder="$t('setting.请选择省市区')"
              />
              <el-input
                v-model="formData['address' + lang]"
                class="ml10"
                style="width: 400px"
                :placeholder="$t('setting.请输入详细地址')"
              />
            </div>
            <div v-if="row.key === 'businessTimes'">
              <div
                class="flex_aic gap-10 mb10"
                v-for="(item, index) in formData.businessTimes"
                :key="index"
              >
                <div class="flex_aic gap-10">
                  <el-time-picker
                    v-model="item.start"
                    style="width: 140px"
                    class="flex-shrink-0"
                    format="HH:mm"
                    value-format="HH:mm"
                    :placeholder="$t('setting.开始时间')"
                  />
                  <div class="color-999999">
                    {{ $t("setting.至") }}
                  </div>
                  <el-time-picker
                    v-model="item.end"
                    style="width: 140px"
                    class="flex-shrink-0"
                    format="HH:mm"
                    value-format="HH:mm"
                    :placeholder="$t('setting.结束时间')"
                  />
                </div>
                <el-icon
                  class="cursor-pointer"
                  @click.stop="deleteBusinessTime(index)"
                  ><Delete
                /></el-icon>
              </div>
              <div
                class="inline-flex items-center cursor-pointer gap-4 color-primary"
                @click="addBusinessTime"
              >
                <el-icon><Plus /></el-icon>
                {{ $t("setting.添加营业时间") }}
              </div>
            </div>
            <div v-if="row.key === 'enableComment'">
              <el-switch
                v-model="formData.enableComment"
                :active-value="1"
                :inactive-value="0"
              />
            </div>
            <div v-if="row.key === 'description'">
              <el-input
                v-model="formData['description' + lang]"
                type="textarea"
                :rows="4"
                style="width: 600px"
                :placeholder="$t('setting.请输入商家介绍')"
              />
            </div>
            <div v-if="row.key === 'tipRate'">
              <el-select v-model="formData.tipRate" style="width: 100px">
                <el-option
                  v-for="item in [10, 20, 30]"
                  :key="item"
                  :label="item"
                  :value="item"
                />
              </el-select>
              %
            </div>
          </div>
        </template>
      </el-table-column>
    </el-table>

    <!-- 底部操作按钮 -->
    <div class="action-buttons">
      <el-button type="primary" @click="handleSave">{{
        $t("setting.保存")
      }}</el-button>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, reactive } from "vue";
import UploadFile from "@/components/UploadFile.vue";
import Api from "@/config/api/api";
import { useI18n } from "vue-i18n";
import { ElMessage } from "element-plus";
import LangTabs from "@/components/langTabs.vue";
import { getLangs, setAttrLangs } from "@/i18n/tools";
import { Delete, Plus } from "@element-plus/icons-vue";
import PickPicture from "@/components/PickPicture.vue";

const { locale, t } = useI18n();
const tenantInfo = ref({});
const originTenantInfo = ref({});
const lang = ref(locale.value);
const loading = ref(false);

// 店铺基本信息数据
const basicInfoData = ref([
  {
    name: t("setting.店铺名称"),
    key: "shopName",
  },
  {
    name: t("setting.店铺Logo"),
    key: "shopLogo",
  },
  {
    name: t("setting.营业状态"),
    key: "tenantOpenStatus",
  },
  {
    name: t("setting.商家介绍"),
    key: "description",
  },
  {
    name: t("setting.店铺相册"),
    key: "album",
  },
  {
    name: t("setting.店铺客服电话"),
    key: "shopPhone",
  },
  {
    name: t("setting.店铺地址"),
    key: "shopAddress",
  },
  {
    name: t("setting.营业时间"),
    key: "businessTimes",
  },
  {
    name: t("setting.是否开启评论"),
    key: "enableComment",
  },
  {
    name: t("setting.小费比例"),
    key: "tipRate",
  },
]);

// 表单数据对象，映射到接口字段
const formData = ref({
  // 店铺基本信息
  // mainSku: "",
  shopLogo: [],
  album: [],
  shopPhone: "",
  shopAddress: [],
  businessTimes: [],
  enableComment: 0,
  tipRate: 0,
  tenantOpenStatus: 0,
});
setAttrLangs(formData.value, "address", "");

const cascaderProps = ref({
  lazy: true,
  label: "name" + locale.value,
  value: "id",
  lazyLoad(node, resolve) {
    const { level } = node;
    Api.getRegion({
      parentId: node.value || 0,
    }).then((res) => {
      if (level == 2) {
        res.data?.forEach((item) => {
          item.children = [];
          item.leaf = true;
        });
      }
      resolve(res.data || []);
    });
  },
});

const addBusinessTime = () => {
  formData.value.businessTimes.push({ start: "", end: "" });
};
const deleteBusinessTime = (index) => {
  formData.value.businessTimes.splice(index, 1);
};
const handleSave = async () => {
  // 营业时间必填
  if (
    formData.value.businessTimes.length == 0 ||
    formData.value.businessTimes.some((item) => !item.start || !item.end)
  ) {
    ElMessage.error(t("setting.请填写营业时间"));
    return;
  }
  try {
    // 构建提交参数
    const params = {
      logo: formData.value.shopLogo?.[0] || "",
      album: formData.value.album.join(","),
      servicePhone: formData.value.shopPhone,
      provinceId: formData.value.shopAddress[0],
      cityId: formData.value.shopAddress[1],
      areaId: formData.value.shopAddress[2],
      businessTimes: formData.value.businessTimes.map((item) => ({
        start: item.start,
        end: item.end,
      })),
      enableComment: formData.value.enableComment,
      tipRate: formData.value.tipRate,
      tenantOpenStatus: formData.value.tenantOpenStatus,
    };
    getLangs().forEach((lang) => {
      params["name" + lang] = formData.value["name" + lang];
      params["address" + lang] = formData.value["address" + lang];
      params["description" + lang] = formData.value["description" + lang];
    });

    // 这里应该调用你的API保存数据
    const res = await Api.tenant_center_config(params);
    if (res.status == 200) {
      ElMessage.success(t("setting.保存成功"));
      getTenantInfo();
    }
  } catch (error) {
    ElMessage.error(t("setting.保存失败，请重试"));
  }
};

// 获取商户信息
const getTenantInfo = async () => {
  loading.value = true;
  try {
    // 模拟API调用获取真实商户信息
    const res = await Api.tenant_current();
    const merchantInfo = res.data;

    // 更新商户信息
    tenantInfo.value = {
      ...merchantInfo,
    };
    originTenantInfo.value = merchantInfo;

    // 将API返回数据映射到表单数据
    formData.value = {
      // 店铺基本信息
      shopLogo: merchantInfo.logo ? [merchantInfo.logo] : [],
      album: merchantInfo.album ? merchantInfo.album?.split(",") : [],
      shopPhone: merchantInfo.servicePhone,
      shopAddress: [
        merchantInfo.provinceId,
        merchantInfo.cityId,
        merchantInfo.areaId,
      ],
      businessTimes: merchantInfo.businessTimes || [],
      enableComment: merchantInfo.enableComment,
      tipRate: merchantInfo.tipRate,
      tenantOpenStatus: merchantInfo.tenantOpenStatus,
    };

    getLangs().forEach((lang) => {
      formData.value["name" + lang] = merchantInfo["name" + lang];
      formData.value["address" + lang] = merchantInfo["address" + lang];
      formData.value["description" + lang] = merchantInfo["description" + lang];
    });
  } catch (error) {
    ElMessage.error(t("setting.获取商户信息失败请重试"));
  } finally {
    loading.value = false;
  }
};

onMounted(() => {
  getTenantInfo();
});
</script>
<style scoped lang="scss">
.titleRow {
  width: 100%;
  height: 36px;
  border-radius: 2px;
  background: rgba(24, 144, 255, 0.05);
  line-height: 36px;
  font-weight: 500;
  color: #333;
  font-size: 16px;
}

.mb20 {
  margin-bottom: 20px;
}

.mb30 {
  margin-bottom: 30px;
}

.action-buttons {
  margin-top: 20px;
  text-align: center;
  padding: 20px 0;
}
</style>
